<?php
 class Linecheckout extends CS_Controller {
 	
     public function _init() {
         
        $this->load->helper(array('common','line','validation'));
        $this->load->library('stream/linestream', null, 'linestream');
        $this->load->model('line_base_model', 'line_base');
        $this->load->model('line_travel_type_model', 'line_travel_type');
        $this->load->model('line_product_type_model', 'line_product_type');
        $this->load->model('line_price_model', 'line_price');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('passengers_model', 'passengers');
        $this->load->model('sales_order_model', 'sales_order');
        $this->load->model('line_order_profit_model', 'line_order_profit');
        $this->load->model('line_order_member_model', 'line_order_member');
        $this->load->model('line_order_product_model', 'line_order_product');
        $this->load->model('fapiao_invoice_model', 'fapiao_invoice');
        $this->load->model('pay_style_model', 'pay_style');
     }
     
     public function view() {
        
         $line_id = $this->input->post('line_id');
         $price_id = $this->input->post('price_id');
         $data['adult_num']    = $this->input->post('adult_num');
         $data['children_num'] = $this->input->post('children_num');
         $line_base = $this->line_base->findViewById($line_id);
         if ($line_base->num_rows() <= 0) {
             $this->alertError('此产品不存在。');
         }
         $data['line_base'] = $line_base->row();
         $line_price = $this->line_price->findById($price_id);
         if (!$line_price) {
             $this->alertError('此产品已下架。');
         }
         $data['current_line_price'] = $line_price->row();
         $data['pay_style']  = $this->pay_style->find();
         $data['passengers'] = $this->passengers->find();
         $data['name'] = '订单填写';
         $data['back_url'] = 'line/lineproduct/view/'.$line_id;
         $data['user_detail'] = $this->user->findByUid($this->uid)->row(0);
         if ($this->validateUserType()) { //验证用户类型，如果是供应商或者是分销商
             $data['lineTraffic'] = lineTraffic(true);
             $data['home_price_show'] = false;
             $this->load->view('line/linecheckout/salesercheckout',$data);
         } else { //如果是散客
             $data['user_account'] = $this->user_account->findByUid($this->uid)->row(0);
             $this->load->view('line/linecheckout/salesercheckout', $data);
         }
     }

    
     /**
      * 供应商页面
      */
     public function ajaxCheckoutSupplierPrice()
     {
         $data = $this->publicPriceCommon();
         echo json_encode(array(
                 'status'          => true,
                 'orderPriceHtml'  => $this->load->view('line/linecheckout/saleser_order_price', $data, true),
         ));exit;
     }
     
     public function publicPriceCommon()
     {
         $data     = array();
         $price_id = $this->input->get_post('price_id');
         $uid      = $this->input->get_post('provUid');
     
         $data['adult_num']    = $this->input->get_post('adult_num');
         $data['children_num'] = $this->input->get_post('children_num');
         $data['amount_bonus'] = $this->input->get_post('amount_bonus');
     
         $result = $this->line_price->findById($price_id);  //当前价格
     
         $data['current_line_price'] = $result->row();
         $data['line_base']  = $this->user->findByUid($uid)->row(0); //当前供应商信息。
         $data['pay_style']  = $this->pay_style->find();
         $data['passengers'] = $this->passengers->find();   //证件类型
         if ($this->input->get_post('home_price') && $this->input->get_post('adult_num')%2 == 1) {
             $data['home_price_show'] = true;
         } else {
             $data['home_price_show'] = false;
         }
         $data['pay_style_scale'] = $this->input->get_post('pay_style_scale');
         return $data;
     }
     
     /**
      * 订单提交方法。
      */
     public function submitOrder()
     {
         $error  = $this->validateSubmitOrderInfo();
         $result = $this->line_price->findById($this->input->post('price_id'));
         $line_price = $result->row();
         if ($this->input->post('line_id') != $line_price->line_id) {
             $error[] = '当前产品与实际产品不符';
         }
         $totalNum = $this->input->post('adult_num') + $this->input->post('children_num');
         if ($line_price->line_stock - $totalNum < 0) {
             $error[] = '当前产品的库存不足';
         }
         if (strtotime(date('Y-m-d', strtotime($line_price->start_date)).' 23:59:59')-$line_price->open_time*60*60 < time()) {
             $error[] = '必须要提前 '.$line_price->open_time.'小时预定，请选择其他时间段。';
         }
         if (!empty($error)) {
             $this->jsonMessage($error);
         }
         $orderProfit = $this->executeProfitClass(); //执行分润操作,获取订单分润数据
         $error = $this->linestream->getError();
         if (!empty($error)) {
             $this->jsonMessage($error);
         }
         $this->db->trans_start();
         //保存订单表
         $orderData = $this->getOrderInfo($this->input->post(), $line_price); //获取当前需保存订单的信息
        
         $order_id  = $this->sales_order->insertSalesOrder($orderData); //保存订单，获取订单order_id
        
         //保存订单分润表
         if (!empty($orderProfit)) {
             $isSaved = $this->line_order_profit->insertIntoOrderProfit($order_id, $orderProfit); //保存订单分润表数据
         }
         //保存游客表
         $saveInsertMember = $this->line_order_member->insertLineOrderMember($order_id, $this->input->post('passengers')); //将数据保存在游客表中。
         
         //保存订单下的产品表
         $saveLineProduct = $this->line_order_product->insertLineOrderProduct($order_id, $line_price, $this->input->post()); //保存订单下的产品
         //保存发票表
         $invoice = $this->input->post('invoice');
         if ($this->input->post('fapiao_invoice') || !empty($invoice)) {
             $fapiaoId = $this->fapiao_invoice->insertFapiaoInvoice($order_id, $this->input->post('invoice')); //保存发票信息
         }
     
         //当前库存减掉。
         $updateStock = $this->line_price->updateLineStock($line_price->id, $totalNum); //更新当前库存。
     
         //销售记录  + 购买数量
         $updateSaleQty = $this->line_base->updateSalesQty($line_price->line_id, $totalNum); //更新购买数量
         $this->db->trans_complete();
     
         if ($this->db->trans_status() === FALSE) {
             $this->jsonMessage('订单提交失败！');
         }
         $line_travel_type = $this->input->post('line_travel_type');
         $this->session->set_userdata('last_order_id', $order_id); //将订单id保存在session中。
         if ($this->input->post('pay_style_type') != 2) { //如果不等于2，属于在线支付
             //给供应商发短信
             if ($line_travel_type == 3) {//如果是短线
                 $this->jsonMessage('', 'line/payment/payOrderLine');
             } else {
                 $this->jsonMessage('', 'line/payment/placeAnOrder');
             }
         } else { //如果是到付，不管长线还是短线，都需要给供应商发短信
             $this->jsonMessage('', 'line/payment/placeAnOrder');
         }
     }
     
     
     private function getOrderInfo($postData, $line_price)
     {
         $orderInfo = array();
         $orderInfo['order_sn']       = date('ynjGis').mt_rand(100, 999); //生成随机的订单号
         $orderInfo['uid']            = $this->uid;//购买者用户uid
         $orderInfo['user_name']      = isset($postData['user_name']) ? $postData['user_name'] : '';
         $orderInfo['telephone']      = isset($postData['telephone']) ? $postData['telephone'] : '';
         $orderInfo['email']          = isset($postData['email']) ? $postData['email'] : '';
         $orderInfo['order_status']   = $postData['line_travel_type'] == 3 ? 2 : 1; //如果是周边旅游（3），则属于短线，订单状态为已确认（2），否则订单状态为待确认。
         $orderInfo['order_remark']   = isset($postData['order_remark']) ? $postData['order_remark'] : '';
         $orderInfo['pay_style_type'] = $postData['pay_style_type']; //支付类型
         $orderInfo['pay_from']       = 2; //1 代表PC端支付   2代表无线端支付
         $orderTotalPrice = $this->getOrderTotalPrice($postData, $line_price);  //求实际要支付的价格
         foreach ($orderTotalPrice as $key => $value) {
             $orderInfo[$key] = $value;
         }
         $orderInfo['created_at'] = date('Y-m-d H:i:s', time());
         $orderInfo['updated_at'] = date('Y-m-d H:i:s', time());
         return $orderInfo;
     }

    /**
     * 实际支付价格
     * @param unknown $postData
     * @param unknown $line_price
     * @return multitype:number NULL
     */
     private function getOrderTotalPrice($postData, $line_price)
     {
        $totalPrice = array();
        $checkoutPayOriginalSubtotal = checkoutPayOriginalSubtotal($line_price, $postData['adult_num'], $postData['children_num']);
        $checkoutPaySubtotal = checkoutPaySubtotal($line_price, $postData['adult_num'], $postData['children_num']);
        //涉及到议价问题。
        $home_price = $this->linestream->home_price != 0 ? $this->linestream->home_price : $postData['home_price'];

        $totalPrice['amount_original_total'] = $checkoutPayOriginalSubtotal + $home_price; //订单销售总价
        $totalPrice['amount_total'] = $checkoutPaySubtotal + $home_price; //订单供应总价
        
        $orderPayTotal = ($this->linestream->orderPayTotal) + $home_price; //获取当前订单需要支付的金额。
        //如果是消费者，且在线支付，则验证是否可以使用UB
        if ($this->input->post('pay_style_type') == 1) { //在线支付
            $pay_bonus = ($line_price->use_ub)*($postData['adult_num']+$postData['children_num']); //支付金币。
            $uid = $this->uid;
            if ($this->userType&UTID_CUSTOMER && $line_price->use_ub > 0 && $this->user_account->validataUserAccountUb($uid, $pay_bonus)) {
                $updateUb = $this->user_account->updateUserAccountUb($uid, $pay_bonus);
                
                $totalPrice['pay_bonus'] = $pay_bonus;
            } else {
                $pay_bonus = 0;
            }
            $orderPayTotal = $orderPayTotal - $pay_bonus;
        }
        
        if ($this->input->post('pay_style_type') == '-9999' && $this->input->post('pay_style_scale') > 0) {
            $totalPrice['pay_style_scale'] = $this->input->post('pay_style_scale');
            $orderPayTotal = $orderPayTotal * $this->input->post('pay_style_scale');
        }
        $orderPayTotal = ceil($orderPayTotal*100)/100; //进位取整，保留两位小数。
        $totalPrice['order_pay_total'] = $orderPayTotal;
        return $totalPrice;
    }
     
     /**
      * 验证提交订单信息
      * return array
      */
     private function validateSubmitOrderInfo()
    {
        $error = array();
        if ($this->validateParam($this->input->post('user_name'))) {
            $error[] = '联系人不能为空';
        }
        if ($this->input->post('adult_num') <= 0) {
            $error[] = '成人数量至少要大于一位';
        }
        if ($this->validateParam($this->input->post('telephone'))) {
            $error[] = '电话号码不能为空';
        }
        if ($this->validateParam($this->input->post('pay_style_type'))) {
            $error[] = '支付方式不能为空';
        }
        if ($this->userType&UTID_PROVIDER) {
            $error[] = '供应商帐号不可购买哦';
        }
        return $error;
     }

     /**
      * 执行分润操作,获取订单分润数据。
      */
     public function executeProfitClass(){
         
         $config = array(
             'price_profit' => 'line_price_profit', //分润表
             'bargaining'   => 'line_bargaining',   //议价表
             'user'         => 'user',              //用户表
         );
         $this->linestream->initialize($config);
         $parameter = array(
            'sellerUid'   => $this->uid, 
            'bitTrade'    => $this->userType,
            'priceId'     => $this->input->post('price_id'),
            'adultNumber' => $this->input->post('adult_num'),
            'childNumber' => $this->input->post('children_num'),
            'bitWan'      => $this->input->post('pay_style_type') == 2 ? 2 : 1,// 选择支付
            'home_price'  => $this->input->post('home_price'),  //单房差
            'pay_style_scale' => $this->input->post('pay_style_scale') ? $this->input->post('pay_style_scale') : 1, //支付百分比
        );
        return $this->linestream->executeLineProfit($parameter);
     }
}